#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSysInfo>
#include "toast.h"

#define QDB 1

QString authorHead;
QString authorName;
QString loginUser="guest";
QString userHead = ":/res/title.jpeg";
QString sysType;
bool isLogin = false;
extern QString pathPre;

QString getTime(QDateTime d)
{
    QString year = QString::number(d.date().year());
    QString month = QString::number(d.date().month());
    QString day = QString::number(d.date().day());
    QString hour = QString::number(d.time().hour());
    QString min = QString::number(d.time().minute());
    QString sec = QString::number(d.time().second());
    return year+month+day+hour+min+sec;
}

void msgBox(QWidget *parent, QMessageBox::Icon icon, QString title, QString msg)
{
    // 创建消息对话框
    QMessageBox * messageBox = new QMessageBox(parent);
    // 设置对话框标题
    messageBox->setWindowTitle(title);
    // 设置对话框中的文本
    messageBox->setText(msg);
    // 设置对话框的图标
    messageBox->setIcon(icon);
    // 添加对话框内的按钮（按钮有QMessageBox自己生成）
    messageBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Save);

    // 模态对话框
    messageBox->setModal(true);
    messageBox->show();
    // messageBox->exec();
    //关闭窗口释放内存
    messageBox->setAttribute(Qt::WA_DeleteOnClose);
}

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 文件队列扫描定时器
    timerFile = new QTimer(this);
    timerFile->setInterval(1000);
    connect(timerFile, SIGNAL(timeout()), this, SLOT(slotTimerFile()));
    timerFile->start();
    // 消息队列扫描定时器
    timerMsg = new QTimer(this);
    timerMsg->setInterval(50);
    connect(timerMsg, SIGNAL(timeout()), this, SLOT(slotTimerMsg()));
    timerMsg->start();

    initUI();
    initTCP();
    qDebug()<< QDir::currentPath();
}
void MainWindow::initTest()
{

    QList<QString> blogPixList, blogUserList, blogTitleList, blogContentList, blogTimeList, blogTypeList, blogPraiseList, blogCollectionList, blogCommentList;

    blogUserList << "user01" << "user01" << "user01" << "user01" << "user01" \
                 << "user02" << "user02" << "user02" << "user02" << "user02" ;
    blogTitleList << "stm32111111111" << "stm32222222" << "stm32333333" << "stm324444444" << "stm3255555" \
                  << "c++ 32111111111" << "c++ 32222222" << "c++ 333333" << "c++ 324444444" << "c++3255555"  ;
    blogTimeList << "2024 12-01 19:58" << "2024 12-01 19:59" << "2024 12-01 19:58" << "2024 12-01 19:48" << "2024 12-01 19:38" \
                 << "2024 12-01 19:58" << "2024 12-01 19:59" << "2024 12-01 19:58" << "2024 12-01 19:48" << "2024 12-01 19:38";
    blogTypeList << "stm32" << "stm32" << "stm32" << "stm32" << "stm32" \
                 << "c++" << "c++" << "c++" << "c++" << "c++" << "c++" ;
    blogPraiseList << "99" <<"89" <<"34" << "56" << "34" \
                   << "101" << "132" << "234" << "45" << "34";
    blogCollectionList << "199" <<"189" <<"134" << "156" << "134" \
                       << "1101" << "1132" << "1234" << "145" << "134";
    blogCommentList << "299" <<"289" <<"234" << "256" << "234" \
                    << "2101" << "2132" << "2234" << "245" << "234";
    blogContentList << "../../../../test/test01.html" << "../../../../test/test02.html"\
                    << "../../../../test/test03.html" << "../../../../test/test04.html" \
                    << "../../../../test/test05.html" << "../../../../test/test06.html" \
                    << "../../../../test/test07.html" << "../../../../test/test08.html"\
                    << "../../../../test/test09.html" << "../../../../test/test10.html";

    QMap<QString, QString> tmp;
    for(int i=0; i<10; i++)
    {
        tmp["blog_pix"] = ":/res/title.jpeg";
        tmp["blog_user"] = blogUserList.at(i);
        tmp["blog_title"] = blogTitleList.at(i);
        tmp["blog_content"] = blogContentList.at(i);
        tmp["blog_time"] = blogTimeList.at(i);
        tmp["blog_type"] = blogTypeList.at(i);
        tmp["blog_praise"] = blogPraiseList.at(i);
        tmp["blog_collection"] = blogCollectionList.at(i);
        tmp["blog_comment"] = blogCommentList.at(i);
        //blogMap.insert(i, tmp);
    }

    QMap<QString, QString> tmp1;
    QList<QString> fileNameList, fileUserList, fileSizeList, fileTileList, filePayList, fileTimeList;
    fileNameList << "1.zip" << "2.tar" << "3.rar" << "4.rar" << "5.rar" \
                 << "6.zip" << "7.rar" << "8.rar" << "9.rar" << "10.zip";
    fileUserList << "user1" << "user1" << "user1" << "user1" << "user1" \
                 << "user2" << "user2" << "user2" << "user2" << "user2";
    fileSizeList << "123b" << "12kb" << "3kb" << "4kb" << "5kb" \
                 << "234b" << "123b" << "23mb" << "12Gb" << "123b";
    filePayList << "1 Q币" << "2 Q币" << "3 Q币" << "4 Q币" << "5 Q币" \
                << "1 Q币" << "2 Q币" << "3 Q币" << "4 Q币" << "5 Q币" ;
    fileTimeList << "20241210091812" << "20241210091312" << "20241210091814" << "20241210091815" << "20241210091816" \
                 << "20241210091812" << "20241210091312" << "20241210091814" << "20241210091815" << "20241210091816";
    fileTileList << "stm32移植手册" << "lvgl移植手册" << "c++指针学习手册" << "qt学习手册，记录学习" << "ceshissdsdsdsd" \
                 << "stm32移植手册" << "lvgl移植手册" << "c++指针学习手册" << "qt学习手册，记录学习" << "ceshissdsdsdsd";
    for(int i=0; i<10; i++)
    {
        tmp1["file_name"] = fileNameList.at(i);
        tmp1["file_user"] = fileUserList.at(i);
        tmp1["file_size"] = fileSizeList.at(i);
        tmp1["file_title"] = fileTileList.at(i);
        tmp1["file_time"] = fileTimeList.at(i);
        tmp1["file_pay"] = filePayList.at(i);
        resMap_c.insert(i, tmp1);
    }
}
void MainWindow::initUI()
{
    // 设置背景色
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(237,243,247));
    this->setPalette(palette);
    // 设置背景图片
    QPixmap pix(":/res/back.jpeg");
    palette.setBrush(QPalette::Background, pix);
    this->setPalette(palette);
    // 设置窗口为屏幕大小
    QRect screenRect = QApplication::desktop()->availableGeometry(QApplication::desktop()->primaryScreen());
    this->resize(screenRect.width(), screenRect.height());
    // 设置窗口标题
    this->setWindowTitle("资源分享平台-客户端");
    this->setWindowIcon(QIcon(":/res/title.jpeg"));
    // 状态栏信息
    statusBar()->showMessage("version 1.0");

    payDialog = new PayDialog();
    connect(payDialog, SIGNAL(signalBtn(int)), this, SLOT(slotPay(int)));
    // 设置整体为垂直布局
    QVBoxLayout *vLayout = new QVBoxLayout();
    ui->centralwidget->setLayout(vLayout);
    ui->centralwidget->setContentsMargins(0, 0, 0, 0);
    vLayout->setContentsMargins(12, 3, 12, 3);

    // 设置顶部菜单
    menuTop = new MenuTop();
    menuTop->setGeometry(0, 0, this->width(), 50);
    vLayout->addWidget(menuTop);
    //设置widget边框 这个设置会影响Widget上的子控件
    //menuTop->setStyleSheet(QString::fromUtf8("border:3px solid blue"));
    connect(menuTop, SIGNAL(signalLabelClicked(enum LabelNnum)), this, SLOT(slotGotoPage(enum LabelNnum)));
    connect(menuTop, SIGNAL(signalTypeChanged(int)), this, SLOT(slotTypeChanged(int)));

    // 测试数据
    //initTest();
    // 主页
    index = new IndexPage();
    connect(index, SIGNAL(labelClicked(QString)), this, SLOT(getIndex(QString)));
    connect(index, SIGNAL(signalBlogInfo(QMap<QString,QString>,int)), this, SLOT(slotBlogInfo(QMap<QString,QString>,int)));
    connect(index, SIGNAL(signalDownloadRes(QMap<QString, QString>)), this, SLOT(slotDownloadRes(QMap<QString, QString>)));
    connect(index, SIGNAL(signalUserRes(QString)), this, SLOT(slotUserRes(QString)));
    if(mainType == 1)
    {
        for(int i=0; i<resMap_c.size(); i++)
        {
            index->addResItem(resMap_c[i]);
        }
    }
    else if(mainType == 0)
    {
        QMap<int, QMap<QString, QString>>::iterator it;
        for(it = blogMap_c.begin(); it != blogMap_c.end(); ++it)
            index->addBlogItem(blogMap_c[it.key()]);
    }

    // 个人主页
    personIndex = new PersonIndex();
    connect(personIndex, SIGNAL(signalBlogClicked(QMap<QString,QString>, QString)), this, SLOT(slotBlogOperation(QMap<QString,QString>, QString)));
    connect(personIndex, SIGNAL(signalBlogClicked(QMap<QString,QString>, int)), this, SLOT(slotBlogOperation(QMap<QString,QString>, int)));
    connect(personIndex, SIGNAL(signalDownloadRes(QMap<QString, QString>)), this, SLOT(slotDownloadRes(QMap<QString, QString>)));
    connect(personIndex, SIGNAL(signalUserRes(QString)), this, SLOT(slotUserRes(QString)));
    connect(personIndex, SIGNAL(signalPublishBlog(QMap<QString, QString>, QList<QString>)), this, SLOT(slotPublishBlog(QMap<QString, QString>, QList<QString>)));
    connect(personIndex, SIGNAL(signalPublishRes(QMap<QString, QString>)), this, SLOT(slotPublishRes(QMap<QString, QString>)));
    connect(personIndex, SIGNAL(signalComment(QString)), this, SLOT(slotComment(QString)));

    // 创建滚动区
    scrollArea = new QScrollArea();
    scrollArea->setContentsMargins(0,0,0,0);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    scrollArea->setWidgetResizable(true);
    scrollArea->setGeometry(QRect(0, 50, this->width(), this->height()));
    // 创建widget
    scrollWidget = new QWidget();
    scrollWidget->setContentsMargins(0,0,0,0);
    // 给widget设置布局
    scrollLayout = new QVBoxLayout(scrollWidget);
    scrollLayout->setMargin(0);
    // 加入子控件， 默认使用软件主页
    scrollLayout->addWidget(index);
    // 设置滚动区核心控件为widget
    scrollArea->setWidget(scrollWidget);
    // 将滚动区加入到垂直布局
    vLayout->addWidget(scrollArea);

    scrollBar = scrollArea->verticalScrollBar();
    connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(slotScrollChanged(int)));

    // 登录对话框
    loginDialog = new LoginDialog();
    connect(loginDialog, SIGNAL(btnClicked(QString)), this, SLOT(getDialogMsg(QString)));
}

/************************************************** tcp process******************************************************************************************/
void MainWindow::initTCP()
{
    tcpClientFile = new QTcpSocket(this);
    tcpClientMessage = new QTcpSocket(this);

    tcpClientFile->connectToHost(HOST_IP, 5555);
    connect(tcpClientFile, SIGNAL(connected()), this, SLOT(fileConnected()));
    connect(tcpClientFile, SIGNAL(readyRead()), this, SLOT(readFile()));
    connect(tcpClientFile, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketErrorFile(QAbstractSocket::SocketError)));
    connect(tcpClientFile, SIGNAL(bytesWritten(qint64)), this, SLOT(slotBytesWritten(qint64)));
    tcpClientMessage->connectToHost(HOST_IP, 6666);
    connect(tcpClientMessage, SIGNAL(connected()), this, SLOT(messageConnected()));
    connect(tcpClientMessage, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(tcpClientMessage, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketErrorMessage(QAbstractSocket::SocketError)));

    loadSize = 4*1024;
    totalRead[0] = 0;
    bytesReaded[0] = 0;
    totalWrite[0] = 0;
    bytesToWrite[0] = 0;
    totalRead[1] = 0;
    bytesReaded[1] = 0;
    totalWrite[1] = 0;
    bytesToWrite[1] = 0;
    fileNameSize = 0;
}

void MainWindow::fileConnected()
{
    //    fileList << "../../../../data/01.jpeg" << "../../../../data/03.jpeg" \
    //                << "../../../../data/03.jpeg" << "../../../../data/04.jpeg" \
    //            << "../../../../data/05.jpeg";
    //    realList << "01.jpeg" << "02.jpeg" << "03.jpeg" << "04.jpeg" << "05.jpeg";
}
void MainWindow::messageConnected()
{
    Toast::instance().show(Toast::INFO, "this is INFO!");
    showType = "index";
    sendMsg << "#MSGSTART#blog_list#C#MSGEND#";
}
void MainWindow::socketErrorMessage(QAbstractSocket::SocketError)
{
    Toast::instance().show(Toast::ERROR, tcpClientMessage->errorString());
    // msgBox(this, QMessageBox::Warning, "socket 错误", tcpClientMessage->errorString());
}

void MainWindow::socketErrorFile(QAbstractSocket::SocketError)
{
    Toast::instance().show(Toast::ERROR, tcpClientFile->errorString());
    //msgBox(this, QMessageBox::Warning, "socket 错误", tcpClientFile->errorString());
}
/************************************************** file process******************************************************************************************/
// 发送token
void MainWindow::sendToken()
{
    // 打开文件
    QFile *tf = new QFile(pathPre+loginUser+"_token.txt");
    if(!tf->open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "writing file error!";
        return;
    }
    // 写入token
    QString tmsg = QString("#MSGSTART#token#") + token + QString("#MSGEND#");
    QTextStream stream(tf);
    stream << tmsg << endl;
    tf->close();
    // 发送token
    fileList << pathPre+loginUser+"_token.txt";
    realList << loginUser+"_token.txt";
}
// 定时扫描文件队列
void MainWindow::slotTimerFile()
{
    QFile file(pathPre + loginUser +".jpeg");
    if(file.exists())
    {
        // 获取用户头像
        QPixmap pix(pathPre + loginUser +".jpeg");
        // 更改用户头像
        menuTop->setPixLogin(&pix);
    }
    if(fileList.length())
        sendFile(fileList.first(), realList.first());
}
// 发送文件头
void MainWindow::sendFile(QString path, QString name)
{
    if(isSendFile==true)
        return;
    if(path==nullptr || name==nullptr)
        return;
    if(path.isNull())
        return;
    if(name.isNull())
        return;
    isSendFile = true;
    qDebug() << "start send file";
    // 打开文件
    sFile = new QFile(path);
    if(!sFile->open(QFile::ReadOnly))
    {
        qDebug() << "open file error!";
        return;
    }
    // 文件总大小
    totalWrite[0] = sFile->size();
    // 打开输出流
    QDataStream sendOut(&outBlock[0], QIODevice::WriteOnly);
    sendOut.setVersion(QDataStream::Qt_5_0);
    // 得到文件名字
    // QString currentFileName = path.right(path.size() - path.lastIndexOf('/')-1);
    // 写入总大小(先用0站位)、文件名大小(先用0站位)、文件名
    sendOut << qint64(0) << qint64(0) << name;
    // 这里的总大小是文件名大小等信息和实际文件大小的总和
    totalWrite[0] += outBlock[0].size();
    bytesToWrite[0] = totalWrite[0];
    // 返回outBolock的开始，用实际的大小信息代替两个qint64(0)空间
    sendOut.device()->seek(0);
    // 写入总大小、文件名大小
    sendOut<<totalWrite[0]<<qint64((outBlock[0].size() - sizeof(qint64)*2));
    // 发送头部数据
    bytesToWrite[0] -= tcpClientFile->write(outBlock[0]);
    // 清空输出流
    outBlock[0].resize(0);
}
// 发送文件正文
void MainWindow::slotBytesWritten(qint64 bytes)
{
    // 发送文件
    if(bytesToWrite[0]>0)
    {
        // 读取一部分数据
        outBlock[0] = sFile->read(qMin(bytesToWrite[0], loadSize));
        // 发送文件
        bytesToWrite[0] -= tcpClientFile->write(outBlock[0]);
        outBlock[0].resize(0);
    }
    else
    {
        qDebug() << "end send file : " << realList.first();
        fileList.removeFirst();
        realList.removeFirst();
        // 关闭文件
        sFile->close();
        // 清空数据
        bytesToWrite[0] = 0;
        totalWrite[0] = 0;
    }
}
// 读取文件
void MainWindow::readFile()
{
    QDataStream in(tcpClientFile);
    in.setVersion(QDataStream::Qt_5_0);
    qDebug() << "read file ...";
    //如果接收到的数据小于等于16个字节，那么是刚开始接收数据，我们保存为头文件信息
    if(bytesReaded[0] <= sizeof(qint64)*2)
    {
        //接收数据总大小信息和文件名大小信息
        if((tcpClientFile->bytesAvailable() >= sizeof(qint64)*2) && (fileNameSize == 0))
        {
            in >> totalRead[0] >> fileNameSize;
            bytesReaded[0] += sizeof(qint64) * 2;
        }
        //接收文件名，并建立文件
        if((tcpClientFile->bytesAvailable() >= fileNameSize) && (fileNameSize != 0))
        {
            in >> fileName;
            bytesReaded[0] += fileNameSize;
            // 创建data目录，所有文件都存放于此
            QDir dir;
            if(!dir.exists(pathPre))
                dir.mkpath(pathPre);
            localFile = new QFile(pathPre+fileName);
            if(!localFile->open(QFile::WriteOnly))
            {
                qDebug() << "writing file error!";
                return;
            }
        }
        else
            return;
    }

    //如果接收的数据小于总数据，那么写入文件
    if(bytesReaded[0] < totalRead[0])
    {
        //bytesReaded[0] += tcpClientFile->bytesAvailable();
        //inBlock[0] = tcpClientFile->readAll();
        qint64 size = qMin(tcpClientFile->bytesAvailable(), totalRead[0]-bytesReaded[0]);
        inBlock[0] = tcpClientFile->read(size);
        bytesReaded[0] += inBlock[0].size();
        localFile->write(inBlock[0]);
        inBlock[0].resize(0);
    }

    //接收数据完成时
    if(bytesReaded[0]  == totalRead[0])
    {
        localFile->close();
        bytesReaded[0]  = 0; // clear for next receive
        totalRead[0] = 0;
        fileNameSize = 0;
        sendFileACK("#MSGSTART#recv_file_over#MSGEND#");
    }
    qDebug() <<"file read over...";
}

void MainWindow::sendFileACK(QString msg)
{
    if(msg.isNull())
        return;
    // 开始传送
    QDataStream sendOut(&outBlock[1], QIODevice::WriteOnly);
    sendOut.setVersion(QDataStream::Qt_5_0);

    // 刚开始发送
    if(totalWrite[1] == 0)
    {
        // 数据总大小，使用占位符
        sendOut << qint64(0) << msg;
        // 得到数据总大小
        totalWrite[1] = outBlock[1].size();
        // 定位到开始
        sendOut.device()->seek(0);
        // 重新设置数据总大小
        sendOut << totalWrite[1];
        // 待发送的总数据
        bytesToWrite[1] = totalWrite[1];
    }
    // 持续发送
    while(bytesToWrite[1] > 0)
    {
        //发送数据
        bytesToWrite[1] -= tcpClientMessage->write(outBlock[1]);
    }
    // 发送完毕，数据清零
    bytesToWrite[1] = 0;
    totalWrite[1] = 0;
    outBlock[1].resize(0);
    qDebug() <<"msg send over...";
}

/************************************************** message process******************************************************************************************/
void MainWindow::slotTimerMsg()
{
    if(isSendMsg==false)
    {
        if(sendMsg.length())
        {
            sendMessage(sendMsg.first());
        }
    }
}
// 发送消息
void MainWindow::sendMessage(QString msg)
{
    if(msg.isNull())
        return;
    // 开始传送
    isSendMsg = true;
    QDataStream sendOut(&outBlock[1], QIODevice::WriteOnly);
    sendOut.setVersion(QDataStream::Qt_5_0);

    // 刚开始发送
    if(totalWrite[1] == 0)
    {
        // 数据总大小，使用占位符
        sendOut << qint64(0) << msg;
        // 得到数据总大小
        totalWrite[1] = outBlock[1].size();
        // 定位到开始
        sendOut.device()->seek(0);
        // 重新设置数据总大小
        sendOut << totalWrite[1];
        // 待发送的总数据
        bytesToWrite[1] = totalWrite[1];
    }
    // 持续发送
    while(bytesToWrite[1] > 0)
    {
        //发送数据
        bytesToWrite[1] -= tcpClientMessage->write(outBlock[1]);
    }
    // 发送完毕，数据清零
    bytesToWrite[1] = 0;
    totalWrite[1] = 0;
    outBlock[1].resize(0);
    qDebug() <<"msg send over...";
}
// 读取消息
void MainWindow::readMessage()
{
    QDataStream in(tcpClientMessage);
    in.setVersion(QDataStream::Qt_5_0);
    qDebug() << "read data...";
    //如果接收到的数据小于等于8个字节，那么是刚开始接收数据，我们保存为数据大小
    if((bytesReaded[1]<sizeof(qint64)) && (totalRead[1] == 0))
    {
        // 接收数据总大小信息和文件名大小信息
        in >> totalRead[1];
        bytesReaded[1] += sizeof(qint64);
    }
    //如果接收的数据小于总数据，那么继续读取数据
    if(bytesReaded[1] < totalRead[1])
    {
        // 剩余的总字节数
        bytesReaded[1] += tcpClientMessage->bytesAvailable();
        QString tmpMsg;
        // 读取数据
        in >> tmpMsg;
        // 追加数据
        recvMsg += tmpMsg;
    }
    //接收数据完成时
    if(bytesReaded[1] == totalRead[1])
    {
        qDebug() << "rec:" << recvMsg;
        msgHandler(recvMsg);
        recvMsg.clear();
        bytesReaded[1] = 0; // clear for next receive
        totalRead[1] = 0;
    }
}
// 处理消息
void MainWindow::msgHandler(QString msg)
{
    QList<QString> strList;
    strList = msg.split("#");
    int leng = strList.length();
    if(strList.at(1)=="MSGSTART" && strList.at(leng-2)=="MSGEND")
    {
        // token
        if(strList.at(2) == "token")
        {
            token = strList.at(3);
        }
        // 登录
        else if(strList.at(2)=="login")
        {
            if(strList.at(3)=="ok")
            {
                isLogin = true;
                //msgBox(this, QMessageBox::Information, "恭喜", "登录成功");
                Toast::instance().show(Toast::INFO, QString("登录成功!"));
                // 更改用户名
                loginUser = loginDialog->getUser();
                menuTop->setUser(loginUser);
                // 发送token
                sendToken();
                sendMsg.removeFirst();
                isSendMsg = false;
            }
            else if(strList.at(3)=="already_login")
            {
                showLogin(0);
                sendMsg.removeFirst();
                isSendMsg = false;
                msgBox(this, QMessageBox::Warning, "错误", "该用户已经登录，请更改用户");
            }
            else if(strList.at(3)=="invalid_user")
            {
                showLogin(0);
                sendMsg.removeFirst();
                isSendMsg = false;
                msgBox(this, QMessageBox::Warning, "错误", "用户名不存在，请输入正确的用户名");
            }
            else if(strList.at(3)=="invalid_passwd")
            {
                showLogin(0);
                sendMsg.removeFirst();
                isSendMsg = false;
                msgBox(this, QMessageBox::Warning, "错误", "密码错误，请输入正确的密码");
            }
        }
        // 注册
        else if(strList.at(2)=="reg")
        {
            if(strList.at(3)=="ok")
            {
                isLogin = true;
                msgBox(this, QMessageBox::Information, "恭喜", "注册成功");
                // 更改用户名
                loginUser = loginDialog->getUser();
                menuTop->setUser(loginUser);
                // 获取用户头像
                QPixmap pix(loginUser+".jpeg");
                // 更改用户头像
                menuTop->setPixLogin(&pix);
                sendMsg.removeFirst();
                isSendMsg = false;
            }
            else if(strList.at(3)=="invalid_user")
            {
                showLogin(1);
                sendMsg.removeFirst();
                isSendMsg = false;
                msgBox(this, QMessageBox::Warning, "错误", "用户名已经存在，请更改用户名");
            }
        }
        else if(strList.at(2) == "recv_file_over")
        {
            isSendFile = false;
        }
        // 博客列表
        else if(strList.at(2) == "append_blog_list" || strList.at(2) == "blog_list")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(4) == "ok")
            {
                for(int i=5; i<=leng-3; i++)
                {
                    parseBlogList(strList.at(i), strList.at(3));
                }
                showMain(strList.at(3));
            }
            else if(strList.at(4) == "failed")
            {
                Toast::instance().show(Toast::INFO, QString("我是有底线的"));
            }
        }
        // 个人主页-博客
        else if(strList.at(2) == "append_user_blog_list" || strList.at(2) == "user_blog_list")
        {
            // 清空数据
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(4) == "ok")
            {
                // 解析数据
                for(int i=5; i<=leng-3; i++)
                {
                    parseUserBlogList(strList.at(i));
                }
                // 显示页面
                showUserBlogList();
            }
            else if(strList.at(4) == "failed")
            {
                Toast::instance().show(Toast::INFO, QString("我是有底线的"));
            }
        }
        // 显示博客内容
        else if(strList.at(2) == "blog_content")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            blogReady = true;
            showUserBlog();
        }
        // 发布博客
        else if(strList.at(2) == "publish_blog")
        {
            if(strList.at(3) == "ok")
            {
                sendMsg.removeFirst();
                isSendMsg = false;
            }
        }
        // 发布资源
        else if(strList.at(2) == "publish_res")
        {
            if(strList.at(3) == "ok")
            {
                sendMsg.removeFirst();
                isSendMsg = false;
            }
        }
        // 资源列表
        else if(strList.at(2) == "append_res_list" || strList.at(2) == "res_list")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(4) == "ok")
            {
                for(int i=5; i<=leng-3; i++)
                {
                    parseResList(strList.at(i), strList.at(3));
                }
                showMain(strList.at(3));
            }
            else if(strList.at(4) == "failed")
            {
                Toast::instance().show(Toast::INFO, QString("我是有底线的"));
            }
        }
        // 个人主页-资源
        else if(strList.at(2) == "append_user_res_list" || strList.at(2) == "user_res_list")
        {
            // 清空数据
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(4) == "ok")
            {
                // 解析数据
                for(int i=5; i<=leng-3; i++)
                {
                    parseUserResList(strList.at(i));
                }
                // 显示页面
                showUserResList();
            }
            else if(strList.at(4) == "failed")
            {
                Toast::instance().show(Toast::INFO, QString("我是有底线的"));
            }
        }
        // 下载
        else if(strList.at(2) == "download_res")
        {
            if(strList.at(3) == "ok")
            {
                sendMsg.removeFirst();
                isSendMsg = false;
                QFile file(pathPre + strList.at(4));
                file.rename(downloadPath + "/" + strList.at(4));
            }
        }
        // 查询点赞
        else if(strList.at(2) == "query_praise")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(3) == "yes")
            {
                personIndex->setPraise(true, praiseNum);
            }
            else
                personIndex->setPraise(false, praiseNum);
        }
        // 查询收藏
        else if(strList.at(2) == "query_collection")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(3) == "yes")
                personIndex->setCollection(true, collectionNum);
            else
                personIndex->setCollection(false, collectionNum);
        }
        // 点赞
        else if(strList.at(2) == "action_praise")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            int praiseNum = personIndex->getPraise().toInt();
            qDebug() << praiseNum;
            if(strList.at(3) == "yes")
            {
                Toast::instance().show(Toast::INFO, QString("成功点赞!!!"));
                personIndex->setPraise(true, QString::number(praiseNum+1));
            }
            else
            {
                Toast::instance().show(Toast::INFO, QString("取消点赞!!!"));
                personIndex->setPraise(false, QString::number(praiseNum-1));
            }
        }
        // 收藏
        else if(strList.at(2) == "action_collection")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            int collectionNum = personIndex->getCollection().toInt();
            if(strList.at(3) == "yes")
            {
                Toast::instance().show(Toast::INFO, QString("收藏成功!!!"));
                personIndex->setCollection(true, QString::number(collectionNum+1));
            }
            else
            {
                Toast::instance().show(Toast::INFO, QString("取消收藏!!!"));
                personIndex->setCollection(false, QString::number(collectionNum-1));
            }
        }
        // 发布评论
        else if(strList.at(2) == "publish_comment")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(3) == "ok")
            {
                // 评论数加1
                commentNum = personIndex->getComment();
                personIndex->setComment(QString::number(commentNum.toInt()+1));
                // 隐藏评论
                personIndex->isShowComment = false;
                personIndex->removeComment();
            }
        }
        // 评论列表
        else if(strList.at(2) == "action_comment")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(3) == "ok")
            {
                // 解析数据
                for(int i=4; i<=leng-3; i++)
                {
                    parseCommentList(strList.at(i));
                }
            }
            // 显示页面
            personIndex->showComment(commentMap);
        }
        // 追加评论列表
        else if(strList.at(2) == "action_append_comment")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(3) == "ok")
            {
                // 解析数据
                for(int i=4; i<=leng-3; i++)
                {
                    parseCommentList(strList.at(i));
                }
            }
            // 显示页面
            personIndex->appendComment(commentMap);
        }
        // 统计收藏、点赞数量
        else if(strList.at(2) == "count_info")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            personIndex->setOtherInfo(strList.at(5), strList.at(6), strList.at(7));
        }
        else if(strList.at(2) == "count_comment" || strList.at(2) == "count_append_comment")
        {
            sendMsg.removeFirst();
            isSendMsg = false;
            if(strList.at(3) == "ok")
            {
                // 解析数据
                for(int i=4; i<=leng-3; i++)
                {
                    parseCommentList(strList.at(i));
                }
                showMsg();
            }
            else if(strList.at(3) == "failed")
            {
                Toast::instance().show(Toast::INFO, QString("只有这些数据"));
            }
            // 显示页面

        }
    }
}
/************************************************** parse data******************************************************************************************/
void MainWindow::parseBlogList(QString msg, QString type)
{
    QList<QString> strList = msg.split("$$");
    QMap<QString, QString> tmp;
    tmp["blog_user"] = strList.at(0);
    tmp["blog_title"] = strList.at(1);
    tmp["blog_overview"] = strList.at(2);
    tmp["blog_time"] = strList.at(3);
    tmp["blog_stamp"] = strList.at(4);
    tmp["blog_praise"] = strList.at(5);
    tmp["blog_collection"] = strList.at(6);
    tmp["blog_comment"] = strList.at(7);
    tmp["blog_type"] = strList.at(8);
    tmp["blog_pay"] = strList.at(9);
    tmp["blog_pix"] = strList.at(10);
    tmp["blog_content"] = strList.at(0) + "_" + strList.at(4) +".html";
    if(type == "C"){ int i = blogMap_c.size(); blogMap_c.insert(i, tmp);}
    else if(type == "C++"){ int i = blogMap_cpp.size(); blogMap_cpp.insert(i, tmp);}
    else if(type == "PHP"){ int i = blogMap_php.size(); blogMap_php.insert(i, tmp);}
    else if(type == "Java"){int i = blogMap_java.size(); blogMap_java.insert(i, tmp);}
    else if(type == "Android"){ int i = blogMap_android.size(); blogMap_android.insert(i, tmp);}
    else if(type == "HarmonyOS"){ int i = blogMap_harmony.size();  blogMap_harmony.insert(i, tmp);}
    else if(type == "STM32"){ int i = blogMap_stm32.size(); blogMap_stm32.insert(i, tmp); }
}

void MainWindow::parseResList(QString msg, QString type)
{
    QList<QString> strList = msg.split("$$");
    QMap<QString, QString> tmp;
    tmp["file_user"] = strList.at(0);
    tmp["file_title"] = strList.at(1);
    tmp["file_name"] = strList.at(2);
    tmp["file_size"] = strList.at(3);
    tmp["file_time"] = strList.at(4);
    tmp["file_stamp"] = strList.at(5);
    tmp["file_type"] = strList.at(6);
    tmp["file_pay"] = strList.at(7);
    tmp["file_dcounts"] = strList.at(8);

    if(type == "C"){ int i = resMap_c.size(); resMap_c.insert(i, tmp);}
    else if(type == "C++"){ int i = resMap_cpp.size(); resMap_cpp.insert(i, tmp);}
    else if(type == "PHP"){ int i = resMap_php.size(); resMap_php.insert(i, tmp);}
    else if(type == "Java"){int i = resMap_java.size(); resMap_java.insert(i, tmp);}
    else if(type == "Android"){ int i = resMap_android.size(); resMap_android.insert(i, tmp);}
    else if(type == "HarmonyOS"){ int i = resMap_harmony.size();  resMap_harmony.insert(i, tmp);}
    else if(type == "STM32"){ int i = resMap_stm32.size(); resMap_stm32.insert(i, tmp); }
}

void MainWindow::parseUserBlogList(QString msg)
{
    QList<QString> strList = msg.split("$$");
    QMap<QString, QString> tmp;
    tmp["blog_user"] = strList.at(0);
    tmp["blog_title"] = strList.at(1);
    tmp["blog_overview"] = strList.at(2);
    tmp["blog_time"] = strList.at(3);
    tmp["blog_stamp"] = strList.at(4);
    tmp["blog_praise"] = strList.at(5);
    tmp["blog_collection"] = strList.at(6);
    tmp["blog_comment"] = strList.at(7);
    tmp["blog_type"] = strList.at(8);
    tmp["blog_pay"] = strList.at(9);
    tmp["blog_pix"] = strList.at(10);
    tmp["blog_content"] = strList.at(0) + "_" + strList.at(4) +".html";

    int i = userBlogMap.size();
    userBlogMap.insert(i, tmp);
}

void MainWindow::parseUserResList(QString msg)
{
    QList<QString> strList = msg.split("$$");
    QMap<QString, QString> tmp;
    tmp["file_user"] = strList.at(0);
    tmp["file_title"] = strList.at(1);
    tmp["file_name"] = strList.at(2);
    tmp["file_size"] = strList.at(3);
    tmp["file_time"] = strList.at(4);
    tmp["file_stamp"] = strList.at(5);
    tmp["file_type"] = strList.at(6);
    tmp["file_pay"] = strList.at(7);
    tmp["file_dcounts"] = strList.at(8);

    int i = userResMap.size();
    userResMap.insert(i, tmp);
}

void MainWindow::parseCommentList(QString msg)
{
    QList<QString> strList = msg.split("$$");
    QMap<QString, QString> tmp;
    tmp["blog_user"] = strList.at(0);
    tmp["blog_name"] = strList.at(1);
    tmp["comment_user"] = strList.at(2);
    tmp["comment_time"] = strList.at(3);
    tmp["comment_content"] = strList.at(4);

    int i=commentMap.size();
    commentMap.insert(i,tmp);
}
/************************************************** menutop process******************************************************************************************/
// 顶部菜单栏跳转
void MainWindow::slotGotoPage(enum LabelNnum lnum)
{
#if QDB
    qDebug() << QString::number(lnum);
#endif
    if(lnum==LABEL_LOGIN)
    {
        showLogin(0);
    }
    else if(lnum == LABEL_MAIN)
    {
        //showType = "index";
        showMain("C");
    }
    else if(lnum == LABEL_PUBLISH)
    {
        if(isLogin)
        {
            scrollLayout->removeWidget(index);
            index->setParent(nullptr);
            scrollLayout->addWidget(personIndex);
            if(mainType == 0)
                personIndex->publishBlog();
            else
                personIndex->publishRes();
        }
    }
    else if(lnum == LABEL_USER)
    {
        if(isLogin)
        {
            if(mainType==0)
            {
                showType = "personIndex";
                // 请求个人博客列表
                userBlogMap.clear();
                QString msg = "#MSGSTART#user_blog_list#" + loginUser + "#MSGEND#";
                sendMsg << msg;
            }
            else if(mainType==1)
            {
                // 请求个人资源列表
                userResMap.clear();
                QString msg = "#MSGSTART#user_res_list#" + loginUser + "#MSGEND#";
                sendMsg << msg;
                showType = "res_personIndex";
            }
        }
    }
    else if(lnum == LABEL_MSG)
    {
        if(isLogin)
        {
            commentMap.clear();
            QString msg = "#MSGSTART#count_comment#" + loginUser + "#MSGEND#";
            sendMsg << msg;
            showType = "msglist";
            msg = QString("#MSGSTART#count_info#") + loginUser + QString("#MSGEND#");
            sendMsg << msg;
        }
        else
        {
            Toast::instance().show(Toast::INFO, QString("请先登录"));
        }
    }
}
// 显示消息列表
void MainWindow::showMsg()
{
    // 删除index
    scrollLayout->removeWidget(index);
    index->setParent(nullptr);
    // 加入personindex
    personIndex->setAuthorName(commentMap[0]["blog_user"]);
    personIndex->setAuthorHead(pathPre + commentMap[0]["blog_user"] + ".jpeg");
    personIndex->removeRight();
    scrollLayout->addWidget(personIndex);
    // 加入个人博客列表
    QMap<int, QMap<QString, QString>>::iterator it;
    for(it = commentMap.begin(); it != commentMap.end(); ++it)
    {
        qDebug() << commentMap[it.key()];
        personIndex->addCommentItem(commentMap[it.key()]);
    }
}

// 显示主页
void MainWindow::showMain(QString type)
{
    // 移除个人主页
    scrollLayout->removeWidget(personIndex);
    personIndex->setParent(nullptr);
    scrollLayout->addWidget(index);
    // 显示整体主页
    index->removeBottom();

    if(mainType == 1)
    {
        showType = "res_index";
        QMap<int, QMap<QString, QString>> map;
        if(type == "C")     map = resMap_c;
        else if(type == "C++")     map = resMap_cpp;
        else if(type == "PHP")     map = resMap_php;
        else if(type == "Java")     map = resMap_java;
        else if(type == "Android")     map = resMap_android;
        else if(type == "HarmonyOS")     map = resMap_harmony;
        else if(type == "STM32")     map = resMap_stm32;
        // 遍历map
        QMap<int, QMap<QString, QString>>::iterator it;
        for(it = map.begin(); it != map.end(); ++it)
        {
            // 添加项目
            index->addResItem(map[it.key()]);
        }
    }
    else if(mainType == 0)
    {
        showType = "index";
        QMap<int, QMap<QString, QString>> map;
        if(type == "C")     map = blogMap_c;
        else if(type == "C++")     map = blogMap_cpp;
        else if(type == "PHP")     map = blogMap_php;
        else if(type == "Java")     map = blogMap_java;
        else if(type == "Android")     map = blogMap_android;
        else if(type == "HarmonyOS")     map = blogMap_harmony;
        else if(type == "STM32")     map = blogMap_stm32;
        // 遍历map
        QMap<int, QMap<QString, QString>>::iterator it;
        for(it = map.begin(); it != map.end(); ++it)
        {
            // 添加项目
            index->addBlogItem(map[it.key()]);
        }
    }
}
// 清除blog数据
void MainWindow::clearBlogMap(QString type)
{

}
// 显示登录对话框
void MainWindow::showLogin(int idx)
{
    loginDialog->changeTab(idx);
    loginDialog->setModal(true);
    loginDialog->show();
    loginDialog->raise();
    loginDialog->activateWindow();
}
// 切换博客/资源
void MainWindow::slotTypeChanged(int type)
{
    mainType = type;
}

// 登录、注册对话框
void MainWindow::getDialogMsg(QString msg)
{
#if QDB
    qDebug() << msg;
#endif
    QList<QString> strList;
    strList = msg.split("#");
    if(strList.at(2) == "login")
    {
        // 发送登录信息
        sendMsg << msg;
    }
    else if(strList.at(2) == "reg")
    {
        // 发送头像
        fileList << strList.at(5);
        realList << strList.at(3)+".jpeg";

        QString sndMsg = "#MSGSTART#reg#"+strList.at(3)+"#"+strList.at(4)+"#MSGEND#";
        // 发送注册信息
        sendMsg << sndMsg;
    }
}

// 页面主页中某个类型的主页
void MainWindow::getIndex(QString type)
{
#if QDB
    qDebug() << type;
#endif
    if(mainType == 0)
    {
        subType = type;
        if(type == "C")             blogMap_c.clear();
        else if(type == "C++")      blogMap_cpp.clear();
        else if(type == "PHP")      blogMap_php.clear();
        else if(type == "Java")     blogMap_java.clear();
        else if(type == "Android")    blogMap_android.clear();
        else if(type == "HarmonyOS")  blogMap_harmony.clear();
        else if(type == "STM32")      blogMap_stm32.clear();
        // 发送消息，请求文章列表
        sendMsg << "#MSGSTART#blog_list#" + type +"#MSGEND#";
        showType = "index";
    }
    else if(mainType == 1)
    {
        subType = type;
        if(type == "C")             resMap_c.clear();
        else if(type == "C++")      resMap_cpp.clear();
        else if(type == "PHP")      resMap_php.clear();
        else if(type == "Java")     resMap_java.clear();
        else if(type == "Android")    resMap_android.clear();
        else if(type == "HarmonyOS")  resMap_harmony.clear();
        else if(type == "STM32")      resMap_stm32.clear();
        // 发送消息，请求资源列表
        sendMsg << "#MSGSTART#res_list#" + type +"#MSGEND#";
        showType = "res_index";
    }
}
/************************************************** personindex process******************************************************************************************/
// 从主页中选中某个博主后，进入博主的个人主页
void MainWindow::slotBlogInfo(QMap<QString,QString> map, int type)
{
#if QDB
    qDebug() << "blof info";
#endif
    praiseNum = map["blog_praise"];
    collectionNum = map["blog_collection"];
    commentNum = map["blog_comment"];
    if(!isLogin)
    {
        Toast::instance().show(Toast::ERROR, "只有登录才可以查看细节!");
        return;
    }
    // 点赞、收藏、评论，只有查看博客细节内容后才可操作
    if(type==2 || type==3 || type==4)
    {
        Toast::instance().show(Toast::WARN, "请查看博客内容后，继续操作!");
        return;
    }
    // 删除index
    scrollLayout->removeWidget(index);
    index->setParent(nullptr);
    // 加入personindex
    scrollLayout->addWidget(personIndex);
    // 显示其中某一篇文章
    if(type == 0)
    {
        if(mainType==0)
        {
            showType = "personBlog";
            blogReady = false;
            QString msg = QString("#MSGSTART#blog_content#")
                    + map["blog_content"] + "#"
                    + map["blog_pix"] + "#"
                    + QString("MSGEND#");
            sendMsg << msg;

            int tout=0;
            QTimer *timer = new QTimer(this);
            QObject::connect(timer, &QTimer::timeout, [=]() mutable{
                tout++;
                personIndex->showBlog(map, 0);
                personIndex->setAuthorName(map["blog_user"]);
                personIndex->setAuthorHead(pathPre + map["blog_user"] + ".jpeg");
                if(blogReady)
                {
                    timer->stop();
                    // 查询点赞、收藏状态
                    QString msg = QString("#MSGSTART#query_praise#") \
                            + loginUser + "#" \
                            + map["blog_user"] + "#" \
                            + map["blog_stamp"] + "#" \
                            + QString("MSGEND#");
                    sendMsg << msg;
                    msg = QString("#MSGSTART#query_collection#") \
                            + loginUser + "#" \
                            + map["blog_user"] + "#" \
                            + map["blog_stamp"] + "#" \
                            + QString("MSGEND#");
                    sendMsg << msg;
                    msg = QString("#MSGSTART#count_info#") + map["blog_user"] +QString("#MSGEND#");
                    sendMsg << msg;

                }
                if(tout>30)
                    timer->stop();
            });
            timer->start(500); // 1000毫秒后触发
        }
    }
    // 显示博主的个人主页
    else if(type == 1)
    {
        showType = "personIndex";
        // 请求个人博客列表
        userBlogMap.clear();
        QString msg = "#MSGSTART#user_blog_list#" + map["blog_user"] + "#MSGEND#";
        sendMsg << msg;
    }
}
// 显示用户个人主页---博客列表
void MainWindow::showUserBlogList()
{
    // 删除index
    scrollLayout->removeWidget(index);
    index->setParent(nullptr);
    // 加入personindex
    personIndex->setAuthorName(userBlogMap[0]["blog_user"]);
    personIndex->setAuthorHead(pathPre + userBlogMap[0]["blog_user"] + ".jpeg");
    personIndex->removeRight();
    scrollLayout->addWidget(personIndex);
    // 加入个人博客列表
    QMap<int, QMap<QString, QString>>::iterator it;
    for(it = userBlogMap.begin(); it != userBlogMap.end(); ++it)
    {
        qDebug() << userBlogMap[it.key()];
        personIndex->addBlogItem(userBlogMap[it.key()]);
    }
}
void MainWindow::showUserResList()
{
    // 删除index
    scrollLayout->removeWidget(index);
    index->setParent(nullptr);
    // 加入personindex
    scrollLayout->addWidget(personIndex);
    personIndex->setAuthorName(userResMap[0]["file_user"]);
    personIndex->setAuthorHead(pathPre + userResMap[0]["file_user"] + ".jpeg");
    personIndex->removeRight();
    // 加入个人资源列表
    QMap<int, QMap<QString, QString>>::iterator it;
    for(it = userResMap.begin(); it != userResMap.end(); ++it)
    {
        personIndex->addResItem(userResMap[it.key()]);
    }
}

void MainWindow::showUserBlog()
{

}

// 某位博主的博客点赞、收藏等操作
void MainWindow::slotBlogOperation(QMap<QString,QString> map, QString action)
{
#if QDB
    qDebug() << "action :" << action;
#endif
    // 点赞
    QString msg;
    if(action == "praise")
    {
        msg = QString("#MSGSTART#action_praise#") \
                + loginUser + "#" \
                + map["blog_user"] + "#" \
                + map["blog_stamp"] + "#" \
                + QString("MSGEND#");
    }
    // 收藏
    else if(action == "collection")
    {
        msg = QString("#MSGSTART#action_collection#") \
                + loginUser + "#" \
                + map["blog_user"] + "#" \
                + map["blog_stamp"] + "#" \
                + QString("MSGEND#");
    }
    // 评论
    else if(action == "comment")
    {
        personIndex->isShowComment = !personIndex->isShowComment;
        qDebug() << personIndex->isShowComment;
        if(personIndex->isShowComment)
        {
            // 查询，展开评论
            commentMap.clear();
            msg = QString("#MSGSTART#action_comment#") \
                    + loginUser + "#" \
                    + map["blog_user"] + "#" \
                    + map["blog_stamp"] + "#" \
                    + QString("MSGEND#");
        }
        else
        {
            // 关闭评论
            personIndex->removeComment();
            return;
        }
    }
    sendMsg << msg;
}

// 某位博主的博客列表中选中一个博客后的操作
void MainWindow::slotBlogOperation(QMap<QString,QString> map,int type)
{
    qDebug() << "blog op";
    // 显示一篇博客
    if(type == 0)
    {
        blogReady = false;
        showType = "psersonBlog";
        QString msg = "#MSGSTART#blog_content#"
                + map["blog_content"] + "#"
                + map["blog_pix"] + "#"
                + "MSGEND#";
        sendMsg << msg;
        QTimer *timer = new QTimer(this);
        QObject::connect(timer, &QTimer::timeout, [=]() {
            personIndex->showBlog(map, 0);
            if(blogReady)
                timer->stop();
        });
        timer->start(500); // 1000毫秒后触发
    }
    // 显示博主的个人主页
    else if(type == 1)
    {
        //personIndex->addBlogItem(blogMap[i]);
    }
    // 点赞
    else if(type == 2 || type == 3 || type == 4)
    {
        Toast::instance().show(Toast::ERROR, "查看具体内容后再操作!");
    }
}

// 发布博客
void MainWindow::slotPublishBlog(QMap<QString, QString> mapInfo, QList<QString> strList)
{
    QMap<QString, QString> map = mapInfo;
    map.insert("blog_comment", "0");
    map.insert("blog_praise", "0");
    map.insert("blog_collection", "0");
    map.insert("blog_user", loginUser);
    QDateTime currentTime = QDateTime::currentDateTime();
    map.insert("blog_time", currentTime.toString());

    // 替换图片名字
    QString blogPre = loginUser + "_" + getTime(currentTime)+"_";
    QString content = map["blog_content"];
    QString pixStr = QString("@");
    for(int i=0; i<strList.length(); i++)
    {
        QString tmp = strList.at(i);
        if(content.contains(tmp))
        {
            // 取图片后缀
            QString nameSuf = tmp.right(tmp.size() - tmp.lastIndexOf('.')-1);
            // 拼接图片名字 user_time_i.png
            QString pixName = blogPre+QString::number(i) + "." + nameSuf;
            // 替换正文中的图片名字
            //content.replace(tmp, pixName);
            // 发送图片
            fileList << tmp;
            realList << pixName;

            pixStr += pixName +"@";

            // 获取图片
            QPixmap insertPix = QPixmap(tmp);
            // 图片宽度、高度
            int pixWidth=insertPix.width();
            int pixHeight = insertPix.height();
            // 允许的最大宽度
            int maxWidth = this->width();
            if(pixWidth>maxWidth)
            {
                pixHeight = (pixHeight / pixWidth) * maxWidth;
                pixWidth = maxWidth;
            }
            // 设置图片居中，使用html语言
            QString htmlStr = "<p align='center'><img src='" + pixName + "' alt='抱歉!图片消失了' width='" + QString::number(pixWidth) + "' height='"+QString::number(pixHeight) + "'/></p><br>";
            // 替换内容为html格式
            content.replace("["+tmp+"]\n", htmlStr);
        }
    }
    // html前缀
    QString htmlHdead="<html><head><meta charset='UTF-8'><title>Document</title></head><body style='background-color: ##E7E6EE;'>";
    // html后缀
    QString htmlEnd = "</body></html>";
    // 组合html内容
    content = htmlHdead + content + htmlEnd;
    // 打开html文件
    QFile *blogFile = new QFile(pathPre + loginUser + "_" + getTime(currentTime) + ".html");
    if(!blogFile->open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "writing file error!";
        return;
    }
    // 写入html
    QTextStream stream(blogFile);
    stream << content;
    blogFile->close();
    // 发送html
    fileList << pathPre + loginUser + "_" + getTime(currentTime) + ".html";
    realList << loginUser + "_" + getTime(currentTime) + ".html";

    // 显示个人主页
    map["blog_content"] = content;
    personIndex->showBlog(map, 1);

    // 发送数据到服务器
    QString msg;
    QString htmlPath = blogPre + ".html";
    map.insert("blog_name", htmlPath);
    map.insert("blog_pix", pixStr);
    map.insert("blog_stamp", getTime(currentTime));
    msg = QString("#MSGSTART#publish_blog")
            + "#" + map["blog_user"]
            + "#" + map["blog_title"]
            + "#" + map["blog_overview"]
            + "#" + map["blog_time"]
            + "#" + map["blog_stamp"]
            + "#" + map["blog_praise"]
            + "#" + map["blog_collection"]
            + "#" + map["blog_comment"]
            + "#" + map["blog_type"]
            + "#" + map["blog_pay"]
            + "#" + map["blog_pix"]
            + QString("#MSGEND#");
    sendMsg << msg;
}
// 发送评论到服务器
void MainWindow::slotComment(QString com)
{
    QString name = personIndex->blogUser + "_" + personIndex->blogStamp;
    QString msg = QString("#MSGSTART#publish_comment#") \
            + personIndex->blogUser +"#" \
            + name + "#" \
            + loginUser + "#" \
            + QDateTime::currentDateTime().toString() + "#" \
            + com + "#" \
            + "MSGEND#";
    sendMsg << msg;
}

// 下载资源
void MainWindow::slotDownloadRes(QMap<QString, QString> map)
{
    // 登录才可下载
    if(!isLogin)
    {
        Toast::instance().show(Toast::ERROR, "只有登录才可以下载资源!");
        return;
    }
    // 付费需要扫码
    if(map["file_pay"] == QString("付费"))
    {
        payDialog->setModal(true);
        payDialog->exec();
        if(!canDownload)
        {
            Toast::instance().show(Toast::ERROR, "取消支付，无法下载!");
            return;
        }
    }

    // 打开目录
    downloadPath = QFileDialog::getExistingDirectory(nullptr, QObject::tr("Open Directory"),
                                                     QDir::homePath());
    QString msg = QString("#MSGSTART#download_res#") + map["file_name"] +QString("#MSGEND#");
    sendMsg << msg;
}
// 支付
void MainWindow::slotPay(int pay)
{
    if(pay == 1)
        canDownload = true;
    else
        canDownload = false;
    payDialog->close();
}

// 显示用户资源
void MainWindow::slotUserRes(QString user)
{
    if(!isLogin)
    {
        Toast::instance().show(Toast::ERROR, "只有登录才可以查看细节!");
        return;
    }
    // 请求个人资源列表
    userResMap.clear();
    QString msg = "#MSGSTART#user_res_list#" + user + "#MSGEND#";
    sendMsg << msg;
    showType = "res_personIndex";
}

// 发布资源
void MainWindow::slotPublishRes(QMap<QString, QString> mapInfo)
{
    QMap<QString, QString> map = mapInfo;
    QDateTime currentTime = QDateTime::currentDateTime();
    map.insert("file_time", currentTime.toString());
    map.insert("file_stamp", getTime(currentTime));
    map.insert("file_user", loginUser);
    map.insert("file_dcounts", QString::number(0));

    QString path = map["file_name"];
    // 截取名字
    QString currentFileName = path.right(path.size() - path.lastIndexOf('/')-1);
    // 文件名加入发送队列
    fileList << path;
    QString realName = loginUser + "_" + getTime(currentTime) + "_" + currentFileName;
    realList << realName;

    // 组合消息
    map["file_name"] = realName;
    QString msg = QString("#MSGSTART#publish_res#")
            + map["file_user"] + "#" \
            + map["file_title"] + "#" \
            + map["file_name"] + "#" \
            + map["file_size"] + "#" \
            + map["file_time"] + "#" \
            + map["file_stamp"] + "#" \
            + map["file_type"] + "#" \
            + map["file_pay"] + "#" \
            + map["file_dcounts"] + "#" \
            + QString("MSGEND#");
    // 格式化大小
    sendMsg << msg;
    qint64 fsize = map["file_size"].toInt();
    if(fsize < 1024)
        map["file_size"] = QString::number(fsize)+" B";
    else if(fsize<1024*2024 && fsize>1024)
        map["file_size"] = QString::number(fsize/1024)+" KB";
    else if(fsize>1024*2024 && fsize<1024*1024*1024)
        map["file_size"] = QString::number(fsize/(1024*1024))+" MB";
    else if(fsize>1024*2024*1024 && fsize<1024*1024*1024*1024)
        map["file_size"] = QString::number(fsize/(1024*1024*1024))+" GB";
    // 显示资源
    personIndex->showRes(map);
}
void MainWindow::slotScrollChanged(int v)
{
    if(scrollBar->value() == scrollBar->maximum())
    {
        if(showType == "index")
        {
            qDebug() << "append blog list";
            sendMsg << "#MSGSTART#append_blog_list#" + subType +"#MSGEND#";
        }
        else if(showType == "personIndex")
        {
            qDebug() << "append user blog list";
            sendMsg << "#MSGSTART#append_user_blog_list#" + subType +"#MSGEND#";
        }
        else if(showType == "res_index")
        {
            qDebug() << "append res list";
            sendMsg << "#MSGSTART#append_res_list#" + subType +"#MSGEND#";
        }
        else if(showType == "res_personIndex")
        {
            qDebug() << "append user res list";
            sendMsg << "#MSGSTART#append_user_res_list#" + subType +"#MSGEND#";
        }
        else if(showType == "personBlog" && personIndex->isShowComment)
        {
            qDebug() << "append comment list";
            QString msg = QString("#MSGSTART#action_append_comment#") \
                    + loginUser + "#" \
                    + personIndex->blogUser + "#" \
                    + personIndex->blogStamp+ "#" \
                    + QString("MSGEND#");
            sendMsg << msg;
        }
        else if(showType == "msglist")
        {
            qDebug() << "append count comment list";
            QString msg = "#MSGSTART#count_append_comment#" + loginUser + "#MSGEND#";
            sendMsg << msg;
        }
    }
}

// 关闭窗口，清除临时文件
void MainWindow::closeEvent(QCloseEvent *event)
{
    // 发送退出登录消息
    QString msg = "#MSGSTART#exit#" + loginUser + "#MSGEND#";
    sendMessage(msg);
    // 删除临时文件
    QDir folder(pathPre);
    if (!folder.exists())
    {
        return;
    }

    QStringList files = folder.entryList(QDir::Files);
    for (const QString& file : files)
    {
        QString filePath = folder.filePath(file);
        QFile::remove(filePath);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

